package org.guegan.util.dircompare.main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.guegan.util.dircompare.bean.DirBean;
import org.hibernate.Query;

public class TreeLoader extends MainModule {
	private static Log log = LogFactory.getLog(TreeLoader.class);
	
	public TreeLoader() {
	}
	
	public void doExecute() {
		Query query = getSession().getNamedQuery("DirBean.loadAll");
		log.debug("Going to run query" + query.getQueryString());
		Map<Long, DirBean> all = new HashMap<Long, DirBean>();
		List<DirBean> roots = new ArrayList<DirBean>(); 
		try {
			List<DirBean> res2 = getSessionUtil().list(query);
			for (DirBean dirBean : res2) {
				all.put(dirBean.getId(), dirBean);
			}
			for (DirBean dirBean : res2) {
				DirBean parent = dirBean.getParent();
				if (parent != null) {
					parent = all.get(parent.getId()); // make sure we are using the right instances, not copies... probably overkill.
					parent.addSubdir(dirBean);
				}
				else {
					roots.add(dirBean);
				}
			}
			result = roots;
		}
		catch (Exception ex) {
			log.error("Error while loading", ex);
			getSession().close();
		}
	}
}
